import React, { useEffect, useState, useRef } from 'react';
import { useModel, history, useSearchParams } from '@umijs/max';
import {
  Form,
  Select,
  Space,
  Button,
  Checkbox,
  Divider,
  Input,
  Radio,
  Card,
} from 'antd';
import styles from './index.less';
// import './index.less'

export default (props) => {
  const { value, onChange, formRef, rentPlan, disabled } = props;
  const { SetRent } = useModel('Goods');
  const [rentData, setRentData] = useState([]);
  const triggerChange = useRef(false);

  useEffect(() => {
    if (value && value.length) {
      setRentData(
        value.map((item) => {
          item.checked = true;
          return item;
        }),
      );
    }
  }, []);

  useEffect(() => {
    if (triggerChange.current) {
      if (rentData && rentData.length) {
        onChange(rentData);
      } else {
        onChange(null);
      }
    } else {
      triggerChange.current = true;
    }
    SetRent(rentData.filter((i) => i.checked).sort((a, b) => a.id - b.id));
  }, [rentData]);

  const onPlanCheck = (target) => {
    const { checked, value } = target;
    let hasItem = false;
    let newList = [];
    newList = rentData.map((item) => {
      if (item.id === value) {
        item.checked = checked;
        hasItem = true;
      }
      return item;
    });

    if (!hasItem) {
      const rentPlanItem = rentPlan.filter((item) => item.id === value)[0];
      const canBuyOutValue = rentPlanItem.show_buyout_option ? 1 : 0;
      const packKey = `package_name_${value}`;
      const packname = formRef.getFieldValue(packKey);
      newList = [
        ...rentData,
        {
          id: value,
          checked,
          support_buyout: canBuyOutValue,
          package_name: rentPlanItem.show_name,
        },
      ];
      if (canBuyOutValue) {
        formRef.setFieldValue(`support_buyout_${value}`, canBuyOutValue);
      }
      if (!packname) {
        formRef.setFieldValue(packKey, rentPlanItem.show_name);
      }
    }
    setRentData(newList);
  };

  const handleChangeBuyOut = (e, id) => {
    const newData = rentData.map((item) => {
      if (item.id === id) {
        item.support_buyout = e;
      }
      return item;
    });
    setRentData(newData);
  };

  const handleChangeRentName = (e, id) => {
    const newData = rentData.map((item) => {
      if (item.id === id) {
        item.package_name = e;
      }
      return item;
    });
    setRentData(newData);
  };

  const handleChangeRentPeriod = (e, id) => {
    const newData = rentData.map((item) => {
      if (item.id === id) {
        const rentPeriod = rentPlan.find((i) => i.id === id)?.rent_period;
        if (rentPeriod) {
          item.rent_period = e
            .sort((a, b) => a - b)
            .map((i) => rentPeriod.find((it) => it.id === i));
        }
      }
      return item;
    });
    setRentData(newData);
  };

  return (
    <Card>
      <Space direction="vertical">
        {rentPlan.map(
          ({ id, show_name, description, show_buyout_option, rent_period }) => {
            const currentData =
              rentData.filter(
                (item) => item.id === id || item.rent_plan_id === id,
              )?.[0] || {};
            const checked = currentData.checked;
            return (
              <div key={id}>
                <Checkbox
                  onChange={(e) => onPlanCheck(e.target)}
                  checked={checked}
                  disabled={disabled}
                  value={id}
                  style={{ marginBottom: checked ? '20px' : '0' }}
                >{`${show_name}（${description}）`}</Checkbox>
                {checked ? (
                  <Card>
                    {show_buyout_option ? (
                      <Form.Item
                        name={`support_buyout_${id}`}
                        key={id}
                        label="是否可买断"
                        rules={[
                          { required: true, message: '请设置是否可买断!' },
                        ]}
                      >
                        <Radio.Group
                          onChange={(e) =>
                            handleChangeBuyOut(e.target.value, id)
                          }
                          disabled={disabled}
                        >
                          <Radio value={1}>是</Radio>
                          <Radio value={0}>否</Radio>
                        </Radio.Group>
                      </Form.Item>
                    ) : null}
                    <Form.Item
                      name={`package_name_${id}`}
                      help="修改名称后将替换小程序上该商品的租赁套餐名称"
                      label="套餐名称"
                    >
                      <Input
                        disabled={disabled}
                        onChange={(e) =>
                          handleChangeRentName(e.target.value, id)
                        }
                      />
                    </Form.Item>
                    <div className={styles.period_content}>
                      <Form.Item
                        name={`period_${id}`}
                        label="租期"
                        rules={[{ required: true, message: '请设置租期!' }]}
                        help="请注意，若展示在支付宝小程序仅支持12个月租期"
                      >
                        <Select
                          options={rent_period.map(({ id, rent_period }) => ({
                            label: rent_period,
                            value: id,
                          }))}
                          mode="multiple"
                          disabled={disabled}
                          style={{ width: '100%' }}
                          onChange={(e) => handleChangeRentPeriod(e, id)}
                          placeholder="请选择租期"
                        />
                      </Form.Item>
                    </div>
                  </Card>
                ) : null}
              </div>
            );
          },
        )}
      </Space>
    </Card>
  );
};
